﻿using System;
using System.Linq;
using System.Reflection;

namespace SvnAPI.Base.Extension
{
    /// <summary>
    /// Class for extension methods.
    /// </summary>
    static class CommandExtension
    {
        #region Methods

        /// <summary>
        /// Get value of the field 'Description' from an Enum that implements 'DisplayAttribute'.
        /// </summary>
        /// <typeparam name="T">Attribute Type.</typeparam>
        /// <param name="enumValue">Value of Enum.</param>
        /// <returns>Return a Descrption from a Enum</returns>
        public static String GetDescription<T>(this Enum enumValue) where T : Attribute
        {
            Attribute attribute = enumValue.GetType().GetTypeInfo().GetDeclaredField(enumValue.ToString()).GetCustomAttribute<T>();

            if (attribute != null)
            {
                PropertyInfo prop = attribute.GetType().GetProperties().Where(x => x.Name == "Description").Take(1).SingleOrDefault();

                if (prop != null)
                {
                    return prop.GetValue(attribute).ToString();
                }
            }

            return String.Empty;
        }
        
        /// <summary>
        /// Get value of the field 'Description' from an Enum that implements 'DisplayAttribute', if is in use.
        /// </summary>
        /// <typeparam name="T">Attribute Type.</typeparam>
        /// <param name="enumValue">Value of Enum.</param>
        /// <param name="IsUsed">Is used?</param>
        /// <returns>Return a Descrption from a Enum</returns>
        public static String GetOptionDescription<T>(this Enum enumValue, Boolean IsUsed) where T : Attribute
        {
            if (IsUsed)
            {
                Attribute attribute = enumValue.GetType().GetTypeInfo().GetDeclaredField(enumValue.ToString()).GetCustomAttribute<T>();

                if (attribute != null)
                {
                    PropertyInfo prop = attribute.GetType().GetProperties().Where(x => x.Name == "Description").Take(1).SingleOrDefault();

                    if (prop != null)
                    {
                        return prop.GetValue(attribute).ToString();
                    }
                }
            }

            return String.Empty;
        }

        #endregion
    }
}
